//
//  MakeExchageHistoryTableViewController.m
//  消费100
//
//  Created by eliot on 16/3/30.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "MakeExchageHistoryTableViewController.h"
#import "MakeExchageHistoryTableViewCell.h"
#import "MJRefresh.h"

#import "SecurityUtil.h"
#import "GTMBase64.h"


#import "UIImageView+WebCache.h"
@interface MakeExchageHistoryTableViewController ()

@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation MakeExchageHistoryTableViewController

static int page = 1;

-(NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)dealloc {
    page = 1;
}

+(MakeExchageHistoryTableViewController*)CreatMakeExchageHistoryTableViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    MakeExchageHistoryTableViewController *MakeExchageHistoryTableViewController=[story instantiateViewControllerWithIdentifier:@"MakeExchageHistoryTableViewController"];
    return MakeExchageHistoryTableViewController;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    /** 注册*/
    [self.tableView registerNib:[UINib nibWithNibName:@"MakeExchageHistoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"MakeExchageHistoryTableViewCell"];
    self.title = @"换购记录";
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
     
//    
//    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    
    UserModel *model = userModel;
    
    /** 换购数据*/
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"consumerId":[SecurityUtil encryptAESData:model.id], @"page":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getAllShopOrder.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataArr = [NSMutableArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];

}

- (void)loadMoreData {
    page += 1;
    UserModel *model = userModel;
    
    /** 换购数据*/
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"consumerId":[SecurityUtil encryptAESData:model.id], @"page":[NSString stringWithFormat:@"%d", page]};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getAllShopOrder.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            [self.dataArr addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     MakeExchageHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MakeExchageHistoryTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.iconIVW.constant = 77 / 320.0 *Width;
    cell.iconIVH.constant = 86 / 320.0 *Width;
    NSArray *tempArr = self.dataArr[indexPath.section];
    NSDictionary *dic1 = tempArr[0];
    NSDictionary *dic2 = tempArr[1];
    
    [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080/%@", dic2[@"productImg"]]]];
    
    cell.titleLb.text = dic2[@"name"];
    cell.priceLb.text = [NSString stringWithFormat:@"￥%.2f", [dic2[@"price"] floatValue]];
    cell.wlNumLb.text = [NSString stringWithFormat:@"￥%.2f", [dic1[@"wlnumber"] floatValue]];
    cell.wlCompany.text = dic1[@"wlcompany"];
    if ([dic1[@"state"] intValue] == 0) {
        cell.stateLb.text = @"未完成";
    }else {
        cell.stateLb.text = @"已完成";
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
        return 10;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (Width <= 320) {
        return 86 / 320.0 *Width + 88 / 320.0 *Width;
    }else {
        return 160 / 320.0 *Width;
    }
   
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
